﻿
using System ;

using MskEdit.Dxf.Model ;
using MskEdit.Sdk ;


namespace MskEdit.Dxf.Backend
{

    public static class DxfLongReader
    {
        internal static long? TryParse( string valueStr, int lineNo, long? fallbackValue ) {
                
            long? maybeLong = SdkValueParser.TryParseToLong( valueStr, null ) ;
            if ( ! maybeLong.HasValue ) {
                SdkDiagnostics.TraceWarning( "Could not parse Long value string.", lineNo ) ;
                return fallbackValue ;
            }
            
            return maybeLong ;
        }


        internal static long? TryRead( string codeStr, string[] allLines, ref int lineNo, long? fallbackValue ) {
        
            int internalLineNo = lineNo ;

            string valueStr = DxfLineReader.TryRead( codeStr, allLines, ref internalLineNo, null ) ;
            if ( valueStr == null ) {
                SdkDiagnostics.TraceWarning( "Could not read group code and Long value string.", internalLineNo ) ;
                return fallbackValue ;
            }
            
            long? maybeLong = TryParse( valueStr, internalLineNo, null ) ;
            if ( ! maybeLong.HasValue )
                return fallbackValue ;
            
            lineNo = internalLineNo ;
            
            return maybeLong ;
        }
        
        
        internal static long? TryReadAfterCode( string[] allLines, ref int lineNo, long? fallbackValue )
        {
            int internalLineNo = lineNo ;
            
            string valueStr = DxfLineReader.TryRead( allLines, ref internalLineNo, null ) ;
            if ( valueStr == null ) {
                SdkDiagnostics.TraceWarning( "Could not read Long value string.", internalLineNo ) ;
                return fallbackValue ;
            }
                 
            long? maybeLong = TryParse( valueStr, internalLineNo, null ) ;
            if ( ! maybeLong.HasValue )
                return fallbackValue ;
            
            lineNo = internalLineNo ;
            
            return maybeLong ;
        }


        internal static long? TryRead( string[] allLines, ref int lineNo, long? fallbackValue ) {
        
            int internalLineNo = lineNo ;
            
            DxfCode dxfCode = DxfCodeReader.TryRead( allLines, ref internalLineNo, null ) ;
            if ( dxfCode == null )
                return fallbackValue ;
            
            if ( ! dxfCode.HasLongCode )
                return fallbackValue ;
            
            long? maybeLong = TryReadAfterCode( allLines, ref internalLineNo, null ) ;
            if ( ! maybeLong.HasValue )
                return fallbackValue ;
                
            lineNo = internalLineNo ;
            
            return maybeLong ;
        }

    }
}
